//
//  Moya+LSF.swift
//  Exam-iOS
//
//  Created by 李胜锋 on 2018/3/6.
//  Copyright © 2018年 李胜锋. All rights reserved.
//

import Foundation
import Moya

protocol LSFTargetType: TargetType {
    var paramaters: [String: Any]? { get }
}

extension LSFTargetType {
    ///添加公共参数
    var task: Task {
        if method == .get {
            let result = Task.requestParameters(parameters: getParameters(paramaters), encoding: URLEncoding.default)
            return result
        }
        else if method == .post {
            let result = Task.requestParameters(parameters: getParameters(paramaters), encoding: JSONEncoding.default)
            return result
        }
        
        return Task.requestPlain
    }
}

//设置默认值
public extension TargetType {
    /// The target's base `URL`.
    var baseURL: URL {
        return URL.init(string: Config.default.baseAPI)!
    }
    
    
    /// The HTTP method used in the request.
    var method: Moya.Method {
        return .get
    }
    
    /// Provides stub data for use in testing.
    var sampleData: Data {
        return Data()
    }

    /// The headers to be used in the request.
    var headers: [String: String]? {
        return ["Content-Type":"application/json"]
    }
}

func getParameters(_ parameters:[String: Any]?) -> [String: Any] {
    var dictionary:[String: Any]
    if parameters != nil {
        dictionary = parameters!
    }
    else {
        dictionary = [String: Any]()
    }
    
    if let token = AccountStorage.default.account.token {
        dictionary["token"] = token
    }
    
    if let uid = AccountStorage.default.account.uid {
        dictionary["uid"] = uid
    }
    
    
    return dictionary
}
